/*
 * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. All rights reserved.
 */
package com.hp.snap.gr.utils.eium;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.siu.utils.LoginContext;
import com.hp.siu.utils.SIUInfo;
import com.hp.snap.gr.utils.CmdUtils;
import com.hp.snap.gr.utils.GRMConfigManager;
import com.hp.usage.jmx.transport.ConnectorFactory;

/**
 * @since 3.2
 * @author Yang, Lin
 * 
 */
public class JMXClientUtils {
    private static JMXConnector jmxConnector;
    private static MBeanServerConnection connection;

	private static Logger logger = LoggerFactory.getLogger(JMXClientUtils.class);
	
    public static synchronized void init() throws Exception {
        if (null != connection) {
            return;
        }

        SIUInfoUtils.init();

        LoginContext loginContext = null;
        if (SIUInfo.getInstance().isSecure()) {
		    logger.info("initial a JMX connector in secure mode!!");
            loginContext = new LoginContext();

            loginContext.init(GRMConfigManager.getUsername(), GRMConfigManager.getPassword());
            jmxConnector = ConnectorFactory.newClient(
                    "iiop:/collectors/ManagementServer/SecureManagementServiceInterface", loginContext);

        } else {
		    logger.info("initial a JMX connector in non-secure mode!!");
            jmxConnector = ConnectorFactory.newClient("iiop:/collectors/ManagementServer/ManagementServiceInterface",
                    loginContext);
        }

        connection = jmxConnector.getMBeanServerConnection();
    }

    public static synchronized void destroy() throws Exception {
        if (null != jmxConnector) {
		    logger.info("destroy a JMX connector !!");
            jmxConnector.close();
        }
    }

    public static Object getAttribute(String mbeanName, String attrName) throws Exception {
        init();

        ObjectName objName = new ObjectName(mbeanName);
        Object value = connection.getAttribute(objName, attrName);
        return value;
    }

    public static Object invokeOperation(String objectName, String operationName, Object[] params, String[] signature)
            throws Exception {
        init();

        ObjectName stdMBeanName = new ObjectName(objectName);
        return connection.invoke(stdMBeanName, operationName, params, signature);
    }

}
